import React, { FC, ReactElement, useCallback } from "react";
import { IAction, Todo, TodoList } from "./types";
import styled from "styled-components";
import { toggleTodoStatus, removeTodo } from "./actions";
import { CompleteIcon } from "./styled";
import TodoItem from "./TodoItem";

interface DragProps {
  drag: boolean;
  setDrag: React.Dispatch<React.SetStateAction<boolean>>;
}

interface IProps extends DragProps {
  todoLists: TodoList;
  dispatch: React.Dispatch<IAction>;
  done?: boolean;
}

const TodoLists: FC<IProps> = ({
  todoLists,
  dispatch,
  done,
  drag,
  setDrag,
}): ReactElement => {
  const handleDone = useCallback(
    id => () => {
      toggleTodoStatus({ id, status: true })(dispatch);
    },
    [dispatch]
  );

  const handleTodo = useCallback(
    id => () => {
      toggleTodoStatus({ id, status: false })(dispatch);
    },
    [dispatch]
  );

  const handleDelete = useCallback(
    id => () => {
      removeTodo(id)(dispatch);
    },
    [dispatch]
  );

  const renderListItem = useCallback(
    (todo: Todo) => (
      <TodoItem
        key={todo._id}
        leftIcon={
          done ? undefined : <CompleteIcon onClick={handleDone(todo._id)} />
        }
        todo={todo}
        handleDelete={handleDelete}
        done={done}
        drag={drag}
        setDrag={setDrag}
        handleDone={handleDone}
        handleTodo={handleTodo}
      />
    ),
    [done, handleDone, handleDelete, drag, setDrag, handleTodo]
  );

  const onDragEnter = useCallback(e => {
    e.stopPropagation();
    console.log(e);
  }, []);

  const onDragOver = useCallback(e => {
    e.preventDefault();
  }, []);

  const onDrop = useCallback(e => {
    e.preventDefault();
    //TODO
    console.log("放到列表中 默认最下边:", e);
  }, []);

  return (
    <ListWrap
      draggable={true}
      onDragEnter={onDragEnter}
      onDragOver={onDragOver}
      onDrop={onDrop}
    >
      {todoLists.map(renderListItem)}
    </ListWrap>
  );
};

export default TodoLists;

const ListWrap = styled.div`
  overflow-y: scroll;
  height: 100%;
  width: 100%;
  margin: 1rem 0;
  padding: 1rem 0.4rem;
`;
